﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace PowerManager
{
	public delegate void FTimerElapsedEventHandler(object sender, EventArgs e);

	public partial class FTimer : MaskedTextBox
	{
		public FTimer()
		{
			InitializeComponent();
			this.Mask = "00:00:00";
			this.Text = "00:00:00";
		}

		private EventTime timer;
		public EventTime Timer
		{
			get { return timer; }
			set
			{
				timer = value;
				if (value == null)
					this.Text = "00:00:00";
				else
					this.Text = value.ToString();
			}
		}

		private bool ParseTimer(string timerStr, out int hours, out int minutes, out int seconds)
		{
			bool ret = true;
			string[] parts = timerStr.Split(':');
			
			try
			{
				hours = int.Parse(parts[0]);
			}
			catch
			{
				hours = 0;
				ret = false;
			}

			try
			{
				minutes = int.Parse(parts[1]);
			}
			catch
			{
				minutes = 0;
				ret = false;
			}

			try
			{
				seconds = int.Parse(parts[2]);
			}
			catch
			{
				seconds = 0;
				ret = false;
			}

			if (minutes > 59)
				minutes = 59;

			if (seconds > 59)
				seconds = 59;

			return ret;
		}

		protected override void OnTextChanged(EventArgs e)
		{
			int hours, minutes, seconds;
			if (this.ParseTimer(this.Text, out hours, out minutes, out seconds))
			{
				this.Text = String.Format("{0:00}", hours) + ':'
							+ String.Format("{0:00}", minutes) + ':'
							+ String.Format("{0:00}", seconds);
			}
			base.OnTextChanged(e);
		}

		public void Start()
		{
			int hours, minutes, seconds;
			ParseTimer(this.Text, out hours, out minutes, out seconds);

			this.Timer = new EventTime(hours, minutes, seconds);
			formTimer.Start();
		}

		public void Stop()
		{
			formTimer.Stop();
		}

		private void formTimer_Tick(object sender, EventArgs e)
		{
			this.Timer = --this.Timer;

			if (this.Timer == 0)
				TimerElapsed(sender, e);
		}

		public event FTimerElapsedEventHandler TimerElapsed;
	}
}
